package cn.wrl.order.service.impl.center;

import cn.wrl.enums.StatusEnum;
import cn.wrl.order.fallback.itemservice.ItemCommonFeignClient;
import cn.wrl.order.mapper.OrderItemsMapper;
import cn.wrl.order.mapper.OrderStatusMapper;
import cn.wrl.order.mapper.OrdersMapper;
import cn.wrl.order.pojo.OrderItems;
import cn.wrl.order.pojo.OrderStatus;
import cn.wrl.order.pojo.Orders;
import cn.wrl.order.pojo.bo.center.OrderItemsCommentsBO;
import cn.wrl.order.service.center.MyCommentsService;
import cn.wrl.service.BaseService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MyCommentsServiceImpl extends BaseService implements MyCommentsService {

    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private ItemCommonFeignClient itemCommentsService;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<OrderItems> queryPendingComment(String orderId) {
        OrderItems queryOrder = new OrderItems();
        queryOrder.setOrderId(orderId);
        return orderItemsMapper.select(queryOrder);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveComments(String userId, String orderId, List<OrderItemsCommentsBO> commentList) {
        //1. 保存评价
        for (OrderItemsCommentsBO oic : commentList) {
            oic.setCommentId(sid.nextShort());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("commentList", commentList);
        itemCommentsService.saveComments(map);

        //2. 修改订单的评价状态
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setIsComment(StatusEnum.YES.type);
        ordersMapper.updateByPrimaryKeySelective(orders);
        //3. 更新订单状态的留言时间
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCommentTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(orderStatus);
    }

}
